package com.io.commonlib.helper

import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader

/**
 * Description:执行脚本的辅助类
 * 2020-08-17 15:15
 * @author LiuMin
 */
class ShellHelper {
    private val TAG = ShellHelper::class.java.simpleName
    fun runScript(command: String, isRoot:Boolean, isNeedResultMsg:Boolean): CommandResult{
        return runScript(mutableListOf(command), isRoot, isNeedResultMsg)
    }

    fun runScript(command: String, isRoot:Boolean): CommandResult{
        return runScript(mutableListOf(command), isRoot, true)
    }

    fun runScript(commands: MutableList<String>, isRoot:Boolean): CommandResult{
        return runScript(commands, isRoot, true)
    }

    fun runScript(commands : MutableList<String>, isRoot:Boolean,
                  isNeedResultMsg:Boolean): CommandResult {
        var process: Process? = null
        var successMsg = StringBuilder()
        var errorMsg = StringBuilder()
        var successResult: BufferedReader? = null
        var errorResult: BufferedReader? = null
        var dataOutputStream: DataOutputStream? = null
        var resultCode = -1
        try {
            process = Runtime.getRuntime().exec(if(isRoot) "su" else "sh")
            dataOutputStream = DataOutputStream(process.outputStream)
            for(command: String in commands){
                dataOutputStream.write(command.toByteArray())
                dataOutputStream.writeBytes("\n")
                dataOutputStream.flush()
            }
            dataOutputStream.writeBytes("exit\n")
            dataOutputStream.flush()
            resultCode = process.waitFor()
            if(isNeedResultMsg){
                successResult = BufferedReader(
                    InputStreamReader(process.inputStream,
                    "UTF-8")
                )
                errorResult = BufferedReader(
                    InputStreamReader(process.errorStream,
                    "UTF-8")
                )
                var str : String?
                while (successResult.readLine().also { str = it} != null){
                    successMsg.append(str)
                }
                while (errorResult.readLine().also { str = it } != null){
                    errorMsg.append(str)
                }
            }
            LogHelper.d(TAG, "successResult:${successResult.toString()}")
            LogHelper.d(TAG, "errorResult:${errorResult.toString()}")
            LogHelper.d(TAG, "runScriptFile--resultCode:$resultCode--successMsg:$successMsg; errorMsg:$errorMsg")
        } catch (e: Exception) {
            e.printStackTrace()
            e?.let {
                it.message?.let {
                        it1->
                    LogHelper.e(TAG, "runScriptFile--Exception:${it1}")
                } ?: let {
                    LogHelper.e(TAG, "runScriptFile--Exception:message 为空")
                }
            }
        } finally {
            dataOutputStream?.close()
            successResult?.close()
            errorResult?.close()
            process?.destroy()
        }
        return CommandResult(resultCode, successMsg.toString(), errorMsg.toString())
    }

    data class CommandResult(
        /**
         * 结果码
         */
        var resultCode: Int,
        /**
         * 成功信息
         */
        var successMsg: String,
        /**
         * 错误信息
         */
        var errorMsg: String
    ) {}
}